package com.example.exam.servlet;

import com.example.exam.dao.StudentDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 修改密码Servlet
 */
@WebServlet("/changePassword")
public class ChangePasswordServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private StudentDAO studentDAO = new StudentDAO();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        // 转发到修改密码页面
        request.getRequestDispatcher("/WEB-INF/views/changePassword.html").forward(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        // 获取学生ID
        String studentId = ((com.example.exam.entity.Student) session.getAttribute("student")).getStudentId();
        
        // 获取表单参数
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");
        
        // 验证新密码和确认密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            request.setAttribute("error", "新密码和确认密码不一致");
            request.getRequestDispatcher("/WEB-INF/views/changePassword.html").forward(request, response);
            return;
        }
        
        // 修改密码
        if (studentDAO.updatePassword(studentId, oldPassword, newPassword)) {
            request.setAttribute("message", "密码修改成功");
        } else {
            request.setAttribute("error", "原密码不正确，密码修改失败");
        }
        
        // 转发到修改密码页面
        request.getRequestDispatcher("/WEB-INF/views/changePassword.html").forward(request, response);
    }
}    